package com.demo.service.impl;

import com.demo.entity.TestEntity;
import com.demo.service.MyTestService;
import com.itdl.lock.anno.RedisLock;
import io.lettuce.core.RedisClient;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class MyTestServiceImpl implements MyTestService {

    @Autowired
    private RedissonClient redissonClient;

    private Integer index = 0;

    @Cacheable(cacheNames = "demo#3", key = "#id")
    public TestEntity getById(Long id){
        TestEntity testEntity = new TestEntity(new Random().nextLong(), UUID.randomUUID().toString(), new Random().nextInt(20) + 10);
        log.info("模拟查询数据库：{}", testEntity);
        return testEntity;
    }

//    @Cacheable(cacheNames = "demo2#3", key = "#id", sync = true)
    public TestEntity getById2(Long id){
        RLock lock = redissonClient.getLock("demo2_lock");
        lock.lock(90, TimeUnit.SECONDS);
        index++;
        try {
            Thread.sleep(50000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("当前线程id:{}", Thread.currentThread().getId());
        log.info("current index is : {}", index);
        TestEntity testEntity = new TestEntity(new Random().nextLong(), UUID.randomUUID().toString(), new Random().nextInt(20) + 10);
        log.info("模拟查询数据库：{}", testEntity);
        lock.unlock();
        return testEntity;
    }


    @Cacheable(cacheNames = "demo3#3", key = "#id", sync = true) // sync表示同步回填缓存
    public TestEntity getById3(Long id){
        TestEntity testEntity;
        RLock lock = redissonClient.getLock("demo3_lock");
        lock.lock(10, TimeUnit.SECONDS);
        try {
            index++;
            log.info("current index is : {}", index);
            if (id > 1000){
                log.info("id={}没有查询到数据，返回空值", id);
                return null;
            }
            testEntity = new TestEntity(new Random().nextLong(), UUID.randomUUID().toString(), new Random().nextInt(20) + 10);
            log.info("模拟查询数据库：{}", testEntity);
        } finally {
            lock.unlock();
        }
        return testEntity;
    }


//    @Cacheable(cacheNames = "demo4#3", key = "#id") // sync表示同步回填缓存
    @RedisLock(lockName = "demo4_lock")
    public TestEntity getById4(Long id) throws InterruptedException {
        index++;
        log.info("current index is : {}", index);
        Thread.sleep(new Random().nextInt(10) * 100);
        TestEntity testEntity = new TestEntity(new Random().nextLong(), UUID.randomUUID().toString(), new Random().nextInt(20) + 10);
        log.info("模拟查询数据库：{}", testEntity);
        return testEntity;
    }
}
